<template>
  <GlobalDrawer
    v-model="visible"
    title="新增案件"
    size="80%"
    :before-close="handleClose"
    @confirm="handleConfirm"
  >
    <div class="drawer-content-wrapper">
      <!-- 关联合同区块 -->
      <div class="form-section" v-if="!isEdit">
        <h3 class="form-section-title">关联合同</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同编号">
                <el-input v-model="contractCode" placeholder="请选择合同" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="　">
                <el-button type="success" @click="openContractSelector">关联合同</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 案件编辑表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="case-edit-form"
      >
        <!-- 基本案情区块 -->
        <div class="form-section">
          <h3 class="form-section-title">基本案情</h3>
          <div class="form-container">
            <!-- 隐藏的合同ID字段 -->
            <el-row :gutter="20" v-if="!isEdit">
              <el-col :span="24">
                <el-form-item label="合同ID" prop="contract_id" style="display: none">
                  <el-input v-model="form.contract_id" type="hidden" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="案件类型" prop="case_type">
                  <el-select
                    v-model="form.case_type"
                    placeholder="请选择案件类型"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(type, index) in CASE_TYPE_OPTIONS"
                      :key="index"
                      :label="type"
                      :value="type"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="案由" prop="case_cause_id">
                  <el-select
                    v-model="form.case_cause_id"
                    placeholder="请输入案由关键词搜索"
                    filterable
                    remote
                    :remote-method="remoteSearchCaseCauses"
                    :loading="caseCauseLoading"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="cause in caseCauseOptions"
                      :key="cause.id"
                      :label="cause.name_with_indent"
                      :value="cause.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="管辖法院" prop="court_id">
                  <el-select
                    v-model="form.court_id"
                    placeholder="请选择管辖法院"
                    style="width: 100%"
                    filterable
                    allow-create
                    @blur="handleCourtBlur('main', $event)"
                  >
                    <el-option
                      v-for="court in courtOptions"
                      :key="court.id"
                      :label="court.name"
                      :value="court.id"
                    />
                    <template #empty>
                      <div style="padding: 10px; text-align: center">
                        <span>没有找到匹配的法院</span>
                        <el-button
                          type="text"
                          size="small"
                          @click="openAddCourt('main')"
                          style="margin-left: 10px"
                        >
                          新增法院
                        </el-button>
                      </div>
                    </template>
                  </el-select>
                  <el-button
                    type="text"
                    size="small"
                    @click="openAddCourt('main')"
                    style="margin-top: 5px"
                  >
                    <el-icon><Plus /></el-icon>
                    新增法院
                  </el-button>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="当前进度" prop="status">
                  <el-select v-model="form.status" placeholder="请选择当前进度" style="width: 100%">
                    <el-option
                      v-for="(status, index) in CASE_STATUS_OPTIONS"
                      :key="index"
                      :label="status"
                      :value="status"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="案件描述" prop="description">
                  <el-input
                    v-model="form.description"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入案件描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 代理信息区块 -->
        <div class="form-section">
          <h3 class="form-section-title">代理信息</h3>
          <div class="form-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="接案日期" prop="entrust_date">
                  <el-date-picker
                    v-model="form.entrust_date"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择接案日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="代理阶段" prop="stage">
                  <el-checkbox-group v-model="selectedStages" class="stage-group">
                    <div class="stage-group-container">
                      <div class="stage-group-section" v-if="filteredStages.length > 0">
                        <el-checkbox
                          v-for="stage in filteredStages"
                          :key="stage.value"
                          :label="stage.value"
                          class="stage-checkbox"
                        >
                          {{ stage.label }}
                        </el-checkbox>
                      </div>
                      <div v-else class="stage-group-section">
                        <span class="text-gray-500">暂无可用阶段选项</span>
                      </div>
                    </div>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="主办律师" prop="main_lawyer">
                  <el-select
                    v-model="form.main_lawyer"
                    placeholder="请选择主办律师"
                    style="width: 100%"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="lawyer in lawyerOptions"
                      :key="lawyer.lawyer_id"
                      :label="lawyer.lawyer_name"
                      :value="lawyer.lawyer_id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="管家" prop="manager">
                  <el-select
                    v-model="form.manager"
                    placeholder="请输入管家名称搜索"
                    filterable
                    remote
                    :remote-method="remoteSearchManagers"
                    :loading="managerLoading"
                    style="width: 100%"
                    :popper-append-to-body="false"
                    clearable
                  >
                    <el-option
                      v-for="manager in managerOptions"
                      :key="manager.id"
                      :label="manager.name"
                      :value="manager.id"
                    >
                      <span>{{ manager.name }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 开庭信息区块 -->
        <div class="form-section">
          <h3 class="form-section-title">开庭信息</h3>
          <div class="form-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开庭处所" prop="court_session_place">
                  <el-select
                    v-model="form.court_session_place"
                    placeholder="请选择开庭处所"
                    style="width: 100%"
                    filterable
                    allow-create
                    @blur="handleCourtBlur('session', $event)"
                  >
                    <el-option
                      v-for="court in courtOptions"
                      :key="court.id"
                      :label="court.name"
                      :value="court.id"
                    />
                    <template #empty>
                      <div style="padding: 10px; text-align: center">
                        <span>没有找到匹配的法院</span>
                        <el-button
                          type="text"
                          size="small"
                          @click="openAddCourt('session')"
                          style="margin-left: 10px"
                        >
                          新增法院
                        </el-button>
                      </div>
                    </template>
                  </el-select>
                  <el-button
                    type="text"
                    size="small"
                    @click="openAddCourt('session')"
                    style="margin-top: 5px"
                  >
                    <el-icon><Plus /></el-icon>
                    新增法院
                  </el-button>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="开庭时间" prop="session_time">
                  <el-date-picker
                    v-model="form.session_time"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    placeholder="请选择开庭时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="出庭律师" prop="session_lawyer">
                  <el-select
                    v-model="form.session_lawyer"
                    placeholder="请选择出庭律师"
                    style="width: 100%"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="lawyer in lawyerOptions"
                      :key="lawyer.lawyer_id"
                      :label="lawyer.lawyer_name"
                      :value="lawyer.lawyer_id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
    </div>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
  import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import request from '@/utils/request'
  import { CASE_STATUS } from '@/constants/lawcase'
  import { useLawcaseStore } from '@/store/lawcase'
  import { GlobalDrawer } from '@/components/common'
  import ContractSelectorDialog from '@/views/lawcase/components/ContractSelectorDialog.vue'
  import AddCourtDialog from '@/views/lawcase/components/AddCourtDialog.vue'

  const CASE_STATUS_OPTIONS = CASE_STATUS

  const CASE_TYPE_OPTIONS = ['民事', '刑事', '行政', '非诉']

  const STAGE_OPTIONS = [
    { label: '其他', value: '其他', group: '其他' },
    { label: '（民）一审阶段', value: '（民）一审阶段', group: '民事' },
    { label: '（民）二审阶段', value: '（民）二审阶段', group: '民事' },
    { label: '（民）调解阶段', value: '（民）调解阶段', group: '民事' },
    { label: '（民）执行阶段', value: '（民）执行阶段', group: '民事' },
    { label: '（刑）一审阶段', value: '（刑）一审阶段', group: '刑事' },
    { label: '（刑）二审阶段', value: '（刑）二审阶段', group: '刑事' },
    { label: '（刑）再审阶段', value: '（刑）再审阶段', group: '刑事' },
    { label: '（行）一审阶段', value: '（行）一审阶段', group: '行政' },
    { label: '（行）二审阶段', value: '（行）二审阶段', group: '行政' },
    { label: '（行）再审阶段', value: '（行）再审阶段', group: '行政' },
  ]

  const civilStages = STAGE_OPTIONS.filter(stage => stage.group === '民事')
  const criminalStages = STAGE_OPTIONS.filter(stage => stage.group === '刑事')
  const administrativeStages = STAGE_OPTIONS.filter(stage => stage.group === '行政')
  const otherStages = STAGE_OPTIONS.filter(stage => stage.group === '其他')

  const filteredStages = computed(() => {
    switch (form.case_type) {
      case '民事':
        return civilStages
      case '刑事':
        return criminalStages
      case '行政':
        return administrativeStages
      case '非诉':
        return otherStages
      default:
        return STAGE_OPTIONS
    }
  })

  interface CaseForm {
    id?: number
    case_code: string
    case_cause_id?: number | null
    court_id: number | null
    court_name?: string
    main_lawyer: number | null
    entrust_date: string
    status: string
    case_type: string
    stage: string
    manager: number | null
    description: string
    session_time: string
    session_court_id: number | null
    court_session_place: number | null
    contract_id: number | null
    session_lawyer: number | null
  }

  interface Lawyer {
    id: number
    lawyer_id: number
    lawyer_name: string
  }

  interface CaseCause {
    id: number
    name: string
    parent_id?: number
    level?: number
    children?: CaseCause[]
    name_with_indent?: string
  }

  interface Court {
    id: number
    name: string
  }

  interface Employee {
    id: number
    name: string
    did: number
  }

  const props = defineProps<{
    modelValue: boolean
    isEdit?: boolean
    caseData?: any
    customerId?: number
    customerName?: string
  }>()

  const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }>()

  const visible = ref(false)
  const formRef = ref<InstanceType<typeof ElForm> | null>(null)

  const form = reactive<CaseForm>({
    case_code: '',
    case_cause_id: null,
    court_id: null,
    court_name: '',
    main_lawyer: null,
    entrust_date: new Date().toISOString().split('T')[0],
    status: '准备阶段（未提交立案）',
    case_type: '民事',
    stage: '',
    manager: null,
    description: '',
    session_time: '',
    session_court_id: null,
    court_session_place: null,
    contract_id: null,
    session_lawyer: null,
  })

  const selectedStages = ref<string[]>([])

  const contractCode = ref<string>('')
  const selectedContractId = ref<number | null>(null)
  const contractSelectorVisible = ref(false)

  const addCourtVisible = ref<boolean>(false)
  const courtTypeToAdd = ref<'main' | 'session'>('main')
  const courtNameToAdd = ref<string>('')

  const caseCauseLoading = ref<boolean>(false)
  const managerLoading = ref<boolean>(false)

  const rules = {
    case_cause_id: [{ required: true, message: '请选择案由', trigger: 'change' }],
    entrust_date: [{ required: true, message: '请选择接案日期', trigger: 'change' }],
    status: [{ required: true, message: '请选择案件状态', trigger: 'change' }],
    case_type: [{ required: true, message: '请选择案件类型', trigger: 'change' }],
    stage: [{ required: true, message: '请至少选择一个代理阶段', trigger: 'change' }],
  }

  const lawyerOptions = ref<Lawyer[]>([])
  const caseCauseOptions = ref<CaseCause[]>([])
  const courtOptions = ref<Court[]>([])
  const managerOptions = ref<Employee[]>([])

  const remoteSearchCaseCauses = async (query: string) => {
    if (query.trim() === '') {
      caseCauseOptions.value = []
      return
    }

    caseCauseLoading.value = true

    try {
      const lawcaseStore = useLawcaseStore()
      const response: any = await lawcaseStore.searchCaseCausesAction(query.trim())
      if (response && response.code === 0) {
        caseCauseOptions.value = response.data || []
      } else {
        caseCauseOptions.value = []
      }
    } catch (error) {
      caseCauseOptions.value = []
    } finally {
      caseCauseLoading.value = false
    }
  }

  const loadLawyerOptions = async () => {
    try {
      const res: any = await request({
        url: '/api/lawcase/cases/get_all_lawyers',
        method: 'get',
        params: {
          page: 1,
          limit: 100,
        },
      })

      if (res.code === 0 && res.data) {
        lawyerOptions.value = res.data
      }
    } catch (error) {
      console.error('获取律师列表失败:', error)
    }
  }

  const loadCourtOptions = async () => {
    try {
      const res: any = await request({
        url: '/api/lawcase/courts/set',
        method: 'get',
      })

      if (res.code === 0 && res.data) {
        courtOptions.value = res.data
      }
    } catch (error) {
      console.error('获取法院列表失败:', error)
    }
  }

  const openAddCourt = (type: 'main' | 'session') => {
    courtTypeToAdd.value = type
    courtNameToAdd.value = ''
    addCourtVisible.value = true
  }

  const handleAddCourtSuccess = (newCourt: Court) => {
    loadCourtOptions()

    if (courtTypeToAdd.value === 'main') {
      form.court_id = newCourt.id
    } else {
      form.court_session_place = newCourt.id
    }

    ElMessage.success('法院添加成功')
  }

  const handleCourtBlur = (type: 'main' | 'session', event: FocusEvent) => {
    const target = event.target as HTMLInputElement
    const inputValue = target.value?.trim()

    if (inputValue && !courtOptions.value.some(court => court.name === inputValue)) {
      ElMessageBox.confirm(`是否将 "${inputValue}" 添加为新法院？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          courtTypeToAdd.value = type
          courtNameToAdd.value = inputValue
          addCourtVisible.value = true
        })
        .catch(() => {
          target.value = ''
        })
    }
  }

  const remoteSearchManagers = async (query: string) => {
    if (query.trim() === '') {
      managerOptions.value = []
      return
    }

    managerLoading.value = true

    try {
      const response: any = await request({
        url: '/api/user/user/search',
        method: 'get',
        params: { keyword: query.trim() },
      })

      if (response && response.code === 0) {
        managerOptions.value = response.data || []
      } else {
        managerOptions.value = []
      }
    } catch (error) {
      managerOptions.value = []
    } finally {
      managerLoading.value = false
    }
  }

  const openContractSelector = () => {
    contractSelectorVisible.value = true
  }

  interface Contract {
    id: number
    code: string
    name: string
  }

  const handleContractSelect = (contract: Contract) => {
    selectedContractId.value = contract.id
    contractCode.value = contract.code
    ElMessage.success(`已选择合同：${contract.name}`)
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          let res: any
          if (props.isEdit) {
            const submitData = {
              ...form,
              id: props.caseData?.id,
            }

            if (form.main_lawyer === null || form.main_lawyer === undefined) {
              submitData.main_lawyer = 0
            }

            if (form.manager === null || form.manager === undefined) {
              submitData.manager = 0
            }

            if (form.session_lawyer === null || form.session_lawyer === undefined) {
              submitData.session_lawyer = 0
            }

            res = await request({
              url: '/api/lawcase/cases/edit',
              method: 'put',
              data: submitData,
            })
          } else {
            const { case_code, ...formDataWithoutCode } = form
            res = await request({
              url: '/api/lawcase/cases/add',
              method: 'post',
              data: {
                ...formDataWithoutCode,
                contract_id: selectedContractId.value,
              },
            })
          }

          if (res.code === 0) {
            ElMessage.success(props.isEdit ? '编辑成功' : '新增成功')
            emit('success')
            handleClose()
          } else {
            ElMessage.error(res.msg || (props.isEdit ? '编辑失败' : '新增失败'))
          }
        } catch (error) {
          console.error('操作失败:', error)
          ElMessage.error(props.isEdit ? '编辑失败' : '新增失败')
        }
      }
    })
  }

  const handleClose = () => {
    emit('update:modelValue', false)
    return true
  }

  const handleConfirm = () => {
    handleSubmit()
  }

  watch(
    () => props.modelValue,
    newVal => {
      visible.value = newVal
      if (newVal) {
        nextTick(async () => {
          await Promise.all([loadLawyerOptions(), loadCourtOptions()])

          if (props.isEdit && props.caseData) {
            Object.keys(form).forEach(key => {
              if (key !== 'stage' && key in props.caseData!) {
                ;(form as any)[key] = props.caseData[key]
              }
            })

            if (props.caseData.stage) {
              selectedStages.value = props.caseData.stage
                .split(',')
                .map((s: string) => s.trim())
                .filter(Boolean)
            } else {
              selectedStages.value = []
            }

            if (props.caseData.contract_id) {
              selectedContractId.value = props.caseData.contract_id
            }
          } else {
            Object.keys(form).forEach(key => {
              if (key !== 'case_code') {
                switch (key) {
                  case 'status':
                    ;(form as any)[key] = '准备阶段（未提交立案）'
                    break
                  case 'case_type':
                    ;(form as any)[key] = '民事'
                    break
                  case 'entrust_date':
                    ;(form as any)[key] = new Date().toISOString().split('T')[0]
                    break
                  default:
                    ;(form as any)[key] = typeof (form as any)[key] === 'string' ? '' : null
                }
              }
            })
            selectedStages.value = []
            selectedContractId.value = null
            contractCode.value = ''
          }
        })
      }
    },
    { immediate: true }
  )

  watch(selectedStages, newVal => {
    form.stage = newVal.join(',')
  })

  watch(
    () => form.case_type,
    (newType, oldType) => {
      if (newType !== oldType) {
        selectedStages.value = []
      }
    }
  )
</script>

<style scoped>
  .drawer-content-wrapper {
    padding: 20px;
  }

  .form-section {
    margin-bottom: 30px;
    position: relative;
  }

  .form-section::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 4px;
    height: 22px;
    background-color: #67c23a;
    border-radius: 2px;
  }

  .form-section-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 10px;
    padding-left: 15px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
  }

  .form-container {
    background-color: #fafafa;
    padding: 20px;
    border-radius: 6px;
    margin-bottom: 20px;
  }

  .case-edit-form {
    padding: 0;
  }

  .el-form-item {
    margin-bottom: 18px;
  }

  .el-input,
  .el-select,
  .el-date-picker {
    width: 100%;
  }

  .el-form-item.is-required .el-form-item__label::before {
    color: #f56c6c;
  }

  .stage-group {
    width: 100%;
  }

  .stage-group-container {
    width: 100%;
  }

  .stage-group-section {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
  }

  .stage-checkbox {
    margin: 0;
    white-space: nowrap;
  }

  .stage-checkbox :deep(.el-checkbox__label) {
    font-size: 14px;
    padding-left: 6px;
  }

  .text-gray-500 {
    color: #909399;
    font-size: 14px;
  }
</style>
